package org.product.controller;

import com.google.gson.Gson;
import org.product.dao.UserDao;
import org.product.entity.User;
import org.product.factory.DaoFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 用户登录
 */
@WebServlet("/api/login.do")
public class UserLoginServlet extends BaseServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 第一：获取页面发送过来的商品信息（合法性验证[略]）
        String username = req.getParameter("username") ;
        String password = req.getParameter("password") ;
        String checkcode = req.getParameter("checkcode") ;

        // 第二：创建实体对象，并封装数据

        // 第三：创建DAO对象，实现数据添加操作
        UserDao userDao = DaoFactory.getUserDaoInstance() ;
        User user = userDao.selectUser(username);

        // 第四：响应结果
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter() ;

        HttpSession session = req.getSession() ;
        System.out.println(session.getId());
        String code = (String)session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY) ;

        if(checkcode==null || !checkcode.equalsIgnoreCase(code)) {
            out.print(new Gson().toJson(errorJson("请输入正确的验证码")));
            return ;
        }

        if(user!=null && password!=null && password.equals(user.getPassword())) {
            session.setAttribute("adminUser",user);
            out.print(new Gson().toJson(successJson(user,200,"登录成功")));
        } else {
            out.print(new Gson().toJson(errorJson("错误的帐号或密码")));
        }

        // 第五：关闭对象
        out.flush();
        out.close();
    }
}
